package com.kaluli.project.service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;

import javax.transaction.Transactional;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.log4j.Logger;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.VisitorSupport;
import org.dom4j.io.SAXReader;
import org.dom4j.tree.DefaultElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import com.kaluli.project.domain.entity.KllMainOrder;
import com.kaluli.project.domain.entity.KllMq;

@Service
@Configuration
@Transactional
public class FtpUtils {

	static Logger log = Logger.getLogger(FtpUtils.class);

	@Autowired
	private  KllMqService kllMqService;
	
	@Autowired
	private  KllMainOrderService kllMainOrderService;

	public String upload(String logSeq, String ftpUrl, String userName, int port, String password,
			String directory, String srcFileName, String destName) throws IOException {
		boolean result = true;
		FTPClient ftpClient = new FTPClient();
		FileInputStream fis = null;
		try {
			ftpClient.setDataTimeout(60000); // 设置传输超时时间为60秒
			ftpClient.setConnectTimeout(30000);// 设置超时时间
			ftpClient.connect(ftpUrl, port);
			ftpClient.login(userName, password);
			ftpClient.enterLocalPassiveMode();
			File srcFile = new File(srcFileName);
			fis = new FileInputStream(srcFile);
			InputStreamReader is = new InputStreamReader(fis, "UTF-8");
			// 设置上传目录
			ftpClient.changeWorkingDirectory(directory);
			ftpClient.setBufferSize(1024);
			// ftpClient.setControlEncoding("utf-8");
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			result = ftpClient.storeFile(destName, fis);
			if (result) {
				return "{status:1}";
			} else {
				return "{status:0}";
			}
			// return result;
		} catch (NumberFormatException e) {
			System.out.println("Ftp port config error");
			throw e;
		} catch (FileNotFoundException e) {
			throw new FileNotFoundException();
		} catch (IOException e) {
			throw new IOException();
		} finally {
			IOUtils.closeQuietly(fis);
			try {
				if (ftpClient.isConnected()) {
					ftpClient.logout();
					ftpClient.disconnect();
				}

			} catch (IOException e) {
				throw new RuntimeException("ftp close exception", e);
			}
		}

	}

	
	public List<Document> retrieve(String remote, String local, String validate, String userName,
			String password, String ftpUrl, int port) throws IOException {
		FTPClient ftpClient = new FTPClient();
		FileInputStream fis = null;
		FTPFile[] files = null;
		List<Document> fileIs = new LinkedList<Document>();
		try {
			ftpClient.setDataTimeout(60000);
			ftpClient.setConnectTimeout(30000);// 设置超时时间
			ftpClient.connect(ftpUrl, port);
			ftpClient.login(userName, password);
			ftpClient.enterLocalPassiveMode();
			ftpClient.changeWorkingDirectory(remote);
			files = ftpClient.listFiles();

			// 获取响应码用于验证是否连接成功
			/*
			 * int reply = ftpClient.getReplyCode(); if
			 * (!FTPReply.isPositiveCompletion(reply)) {
			 * System.out.println("连接不成功"); System.exit(1); }
			 */
			for (FTPFile file : files) {
				// File localFile = new File(local + "/" + file.getName());
				// OutputStream is = new FileOutputStream(localFile);

				SAXReader saxReadr = new SAXReader();
				InputStream is = ftpClient.retrieveFileStream(file.getName());

				Document document = saxReadr.read(is);
				Element root = document.getRootElement();// 得到根节点
				Element ec = (Element) root.selectSingleNode("//OrgMessageID");
				KllMq kllmq = kllMqService.findByMsgId(ec.getText());

				log.info("Gj___回执信息=====" + document.asXML());
				InputStream fi = new ByteArrayInputStream(document.asXML().getBytes("UTF-8"));
				fileIs.add(document);
				File localFile = new File(local + "/gj/" + file.getName());
				localFile.createNewFile();
				OutputStream out = new FileOutputStream(localFile);
				// ftpClient.retrieveFile(file.getName(), out);
				// ftpClient.retrieveFile(file.getName(), out);
				byte[] buffer = new byte[1024];
				int i = -1;
				while ((i = fi.read(buffer)) != -1) {
					out.write(buffer, 0, i);
				}
				out.flush();
				out.close();
				fi.close();

				// 查询到相关记录,可以删除回执文件
				if (kllmq != null) {

					ftpClient.completePendingCommand();
					ftpClient.deleteFile(file.getName());
				}

			}
			// }
			// downloadFile(ftpClient,remote,local,validate);
			// ftpClient.changeWorkingDirectory(remote);

		} catch (NumberFormatException e) {
			System.out.println("Ftp port config error");
			throw e;
		} catch (FileNotFoundException e) {
			throw new FileNotFoundException();
		} catch (IOException e) {
			e.printStackTrace();
			throw new IOException();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.info("FtpUtils:GJ:DocumentException=" + e.getMessage());
		} catch (Exception e) {
			log.info("FtpUtils:GJ:Exception=" + e.getMessage());
		} finally {
			IOUtils.closeQuietly(fis);
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				throw new RuntimeException("ftp close exception", e);
			}
		}
		return fileIs;
	}

	public List<Document> retrieveHG(String remote, String local, String validate, String userName,
			String password, String ftpUrl, int port) throws IOException {
		FTPClient ftpClient = new FTPClient();
		InputStream fis = null;
		FTPFile[] files = null;
		List<Document> fileIs = new LinkedList<Document>();
		try {
			ftpClient.setDataTimeout(60000);
			ftpClient.setConnectTimeout(30000);// 设置超时时间
			ftpClient.connect(ftpUrl, port);
			ftpClient.login(userName, password);
			ftpClient.enterLocalPassiveMode();
			ftpClient.changeWorkingDirectory(remote);
			files = ftpClient.listFiles();
			for (FTPFile file : files) {
				// File localFile = new File(local + "/" + file.getName());
				// OutputStream is = new FileOutputStream(localFile);
				if (!file.getName().equals(".") && !file.getName().equals("..")) {

					SAXReader saxReadr = new SAXReader();
					InputStream is = ftpClient.retrieveFileStream(file.getName());

					Document document = saxReadr.read(is);
					document.accept(new NameSpaceCleaner());
					Element root = document.getRootElement();// 得到根节点
					String guid = root.attributeValue("guid");
					KllMq kllmq = kllMqService.findByMsgId(guid);

					Element ele = ((Element) root.selectSingleNode("/CEB312Message/OrderReturn/returnStatus"));
					if(ele == null){
						ftpClient.completePendingCommand();
						ftpClient.deleteFile(file.getName());
					}else{
						
						String returnStatus = ((Element) root.selectSingleNode("/CEB312Message/OrderReturn/returnStatus"))
								.getText();
						String orderNo = ((Element) root.selectSingleNode("/CEB312Message/OrderReturn/orderNo"))
								.getText();
						KllMainOrder order = kllMainOrderService.findKllMainOrderByIbillingNumber(orderNo);
						log.info("HGZS___回执信息=====" + document.asXML());
						InputStream fi = new ByteArrayInputStream(document.asXML().getBytes("UTF-8"));
						fileIs.add(document);
						File localFile = new File(local + "/hg/" + file.getName());
						localFile.createNewFile();
						OutputStream out = new FileOutputStream(localFile);
						// ftpClient.retrieveFile(file.getName(), out);
						byte[] buffer = new byte[1024];
						int i = -1;
						while ((i = fi.read(buffer)) != -1) {
							out.write(buffer, 0, i);
						}
						out.flush();
						out.close();
						fi.close();
						
						if (order != null) {
							
							ftpClient.completePendingCommand();
							ftpClient.deleteFile(file.getName());
						}
					}
					
					/*if(StringUtils.isNotBlank(returnStatus) && returnStatus.equals("120")){
						ftpClient.completePendingCommand();
						ftpClient.deleteFile(file.getName());
					}*/
				}

			}
			// }
			// downloadFile(ftpClient,remote,local,validate);
			// ftpClient.changeWorkingDirectory(remote);

		} catch (NumberFormatException e) {
			System.out.println("Ftp port config error");
			throw e;
		} catch (FileNotFoundException e) {
			throw new FileNotFoundException();
		} catch (IOException e) {
			e.printStackTrace();
			throw new IOException();
		} catch (DocumentException e) {
			log.info("FtpUtils:HG:DocumentException=" + e.getMessage());
		} catch (Exception e) {
			log.info("FtpUtils:HG:Exception=" + e.getMessage());
		} finally {
			IOUtils.closeQuietly(fis);
			try {
				// ftpClient.disconnect();
				if (ftpClient.isConnected()) {
					ftpClient.logout();
					ftpClient.disconnect();
				}
			} catch (IOException e) {
				throw new RuntimeException("ftp close exception", e);
			}
		}
		return fileIs;
	}

	
	private static final class NameSpaceCleaner extends VisitorSupport {
		public void visit(Document document) {
			((DefaultElement) document.getRootElement()).setNamespace(Namespace.NO_NAMESPACE);
			document.getRootElement().additionalNamespaces().clear();
		}

		public void visit(Namespace namespace) {
			namespace.detach();
		}

		public void visit(Attribute node) {
			if (node.toString().contains("xmlns") || node.toString().contains("xsi:")) {
				node.detach();
			}
		}

		public void visit(Element node) {
			if (node instanceof DefaultElement) {
				((DefaultElement) node).setNamespace(Namespace.NO_NAMESPACE);
			}
		}
	}
	

	public static void main(String s[]) {
		String ftpUrl = "121.33.205.117";
		String username = "shrkmygs";
		String password = "0ijmxggjKT";
		String orderIn = "/4200.IMPBA.SWBEBTRADE.REPORT/in/"; // 即是接口
																// 又是目录
																// 订单推送接口
		String orderOut = "/4200.IMPBA.SWBEBTRADE.REPORT/out/"; // 即是接口
																// 又是目录
																// 处理回执接口

		String local = "/Users/zyzowen1944/project/kaluli_web/ftpdoc";
		java.util.Date current = new java.util.Date();
		java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
		System.out.println(sdf.format(current));

		try {
			// FtpUtils.upload("", ftpUrl, username, 21, password, orderIn,
			// "/Users/zyzowen1944/project/kaluli_web/ftpdoc/661101_20160214160923001.xml",
			// "661101_20160214160923001.xml");
			FtpUtils ftpUtils = new FtpUtils();
			List<Document> filsIs = ftpUtils.retrieve(orderOut, local, "", username, password, ftpUrl, 2221);
			for (Document is : filsIs) {

				Element root = is.getRootElement();// 得到根节点
				// String name =
				// root.getPath("//body")element("OrgMessageID").getText();//
				// 得到单词名
				Element ec = (Element) root.selectSingleNode("//OrgMessageID");
				System.out.println(root.asXML());
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
